package wallet

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ UserTransferToGameFlowModel = (*customUserTransferToGameFlowModel)(nil)

type (
	// UserTransferToGameFlowModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserTransferToGameFlowModel.
	UserTransferToGameFlowModel interface {
		userTransferToGameFlowModel
		InsertTrans(ctx context.Context, tx sqlx.Session, data *UserTransferToGameFlow) (sql.Result, error)
		UpdateStateTrans(ctx context.Context, tx sqlx.Session, flowNo int64, exFlow string, state int64) error
		UpdateState(ctx context.Context, flowNo int64, exFlow string, errMsg string, state int64) error
	}

	customUserTransferToGameFlowModel struct {
		*defaultUserTransferToGameFlowModel
	}
)

// NewUserTransferToGameFlowModel returns a model for the database table.
func NewUserTransferToGameFlowModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserTransferToGameFlowModel {
	return &customUserTransferToGameFlowModel{
		defaultUserTransferToGameFlowModel: newUserTransferToGameFlowModel(conn, c, opts...),
	}
}

func (m *customUserTransferToGameFlowModel) InsertTrans(ctx context.Context, tx sqlx.Session, data *UserTransferToGameFlow) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, userTransferToGameFlowRowsExpectAutoSet)
	ret, err := tx.ExecCtx(ctx, query, data.FlowNo, data.ExternalFlowNo, data.Uid, data.MoneyType, data.MoneyAmount, data.ProviderId, data.State, data.ErrMsg)
	return ret, err
}

func (m *customUserTransferToGameFlowModel) UpdateStateTrans(ctx context.Context, tx sqlx.Session, flowNo int64, exFlow string, state int64) error {
	query := fmt.Sprintf("update %s set state = ?, external_flow_no = ? where flow_no = ?", m.table)
	rs, err := tx.ExecCtx(ctx, query, state, exFlow, flowNo)
	if err != nil {
		return err
	}
	affected, err := rs.RowsAffected()
	if err != nil {
		return err
	}
	if affected == 0 {
		return ErrNotFound
	}
	return nil
}

func (m *customUserTransferToGameFlowModel) UpdateState(ctx context.Context, flowNo int64, exFlow string, errMsg string, state int64) error {
	query := fmt.Sprintf("update %s set state = ?, external_flow_no = ?, err_msg = ? where flow_no = ?", m.table)
	rs, err := m.ExecNoCacheCtx(ctx, query, state, exFlow, errMsg, flowNo)
	if err != nil {
		return err
	}
	affected, err := rs.RowsAffected()
	if err != nil {
		return err
	}
	if affected == 0 {
		return ErrNotFound
	}
	return nil
}
